package com.along.aop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

/*
 * @Author: liujinyi
 * @DateTime: 2025/2/21 15:30
 */
public class LoggingAspect {
  // 定义切点：匹配 UserService 的所有方法
  @Pointcut("execution(* com.along.aop.service.UserService.*(..))")
  public void userServiceMethods() {}

  // Before Advice：在目标方法执行前记录日志
  @Before("userServiceMethods()")
  public void logBefore(JoinPoint joinPoint) {
    System.out.println("方法执行前: " + joinPoint.getSignature().getName());
  }

  // After Returning Advice：在目标方法成功执行后记录日志
  @AfterReturning("userServiceMethods()")
  public void logAfterReturning(JoinPoint joinPoint) {
    System.out.println("方法成功执行后: " + joinPoint.getSignature().getName());
  }

  // After Throwing Advice：在目标方法抛出异常后记录日志
  @AfterThrowing(pointcut = "userServiceMethods()", throwing = "ex")
  public void logAfterThrowing(JoinPoint joinPoint, Exception ex) {
    System.out.println("方法抛出异常后: " + joinPoint.getSignature().getName() + ", 异常: " + ex.getMessage());
  }

  // Around Advice：在目标方法执行前后都记录日志
  @Around("userServiceMethods()")
  public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("方法执行前（Around）: " + joinPoint.getSignature().getName());
    Object result = joinPoint.proceed(); // 调用目标方法
    System.out.println("方法执行后（Around）: " + joinPoint.getSignature().getName());
    return result;
  }

}
